package com.xingdata.jjxc.activity;

import java.io.File;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.AsyncRun;
import com.xingdata.jjxc.App;
import com.xingdata.jjxc.Common;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.base.Base1Activity;
import com.xingdata.jjxc.enty.RespEntity;
import com.xingdata.jjxc.http.HttpResponseListener;
import com.xingdata.jjxc.http.HttpUtil;
import com.xingdata.jjxc.utils.Log;
import com.xingdata.jjxc.utils.SDCardTools;
import com.xingdata.jjxc.utils.SharedPreTools;
import com.xingdata.jjxc.utils.SystemInfo;
import com.xingdata.jjxc.utils.ThreadPoolManager;
import com.xingdata.jjxc.utils.Tools;
import com.xingdata.jjxc.utils.VideoTools;
import com.xingdata.jjxc.utils.ViewTools;

/**
 * 发布视频
 */
public class VideoUploadActivity extends Base1Activity implements
		OnClickListener {
	private boolean cancelUpload;
	private long uploadLastTimePoint;
	private long uploadLastOffset;
	private long uploadFileLength;
	private UploadManager uploadManager;
	private String TAG = "VideoUploadActivity";
	private HashMap<String, String> map;
	private String pathName_img = "img.";
	private String pathName_video = "video.";
	private String pathHead = "http://";
	private String url;
	private EditText titleText;
	private TextView locationTextView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uploadManager = new UploadManager();
		findViewById(R.id.upload_video).setOnClickListener(this);
		titleText = (EditText) findViewById(R.id.video_title);
		locationTextView=(TextView) findViewById(R.id.video_location);
		initData();
	}

	private void initData() {
		Bundle bundle = getIntent().getExtras();
		url = bundle.getString("url");
		locationTextView.setText(SharedPreTools.getString(this, Common.LOACTION, "未知"));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;

		case R.id.upload_video:
			if (titleText.getText().toString().trim().length() == 0) {
				showToast("标题不能为空");
				return;
			}
			showProgressDialog("正在上传视频");

			// 这里判断一下 如果Token为空的时候才重新获取Token否者直接上传视频
			if (SystemInfo.getTokenEntity() != null
					&& SystemInfo.getTokenEntity().getJjxcvideoToken() != null) {
				ThreadPoolManager.getInstance().addTask(
						new uploadFileThread(0, url, null));
			} else {
				getToken(url);
			}
			break;
		}
	}

	@Override
	protected int getContentViewId() {
		return R.layout.video_upload;
	}

	@Override
	protected String getTitleText() {
		return "发布视频";
	}

	@Override
	protected void initViews() {
		((ImageView) findViewById(R.id.title_back)).setOnClickListener(this);
	}

	/**
	 * 上传文件之前先获取Token
	 */
	private void getToken(final String url) {
		map = new HashMap<String, String>();
		map.put("userid", SystemInfo.getUserInfo().getUserid());
		map.put("access_token", SystemInfo.getTokenEntity().getToken());
		map.put("package_name", "com.xingdata.jjxc");
		map.put("bucket", "jjxcimg,jjxcvideo");
		HttpUtil.getInstance(VideoUploadActivity.this).Post(
				App.ZZD_REQUEST_GETUPLOADTOKEN, map,
				new HttpResponseListener() {
					@Override
					public void onSuccess(RespEntity respEntity) {
						JSONObject jsonObject;
						try {
							jsonObject = new JSONObject(respEntity.getResult()
									.toString());
							SystemInfo.getTokenEntity().setJjxcimgToken(
									jsonObject.optString("jjxcimgToken"));
							SystemInfo.getTokenEntity().setJjxcvideoToken(
									jsonObject.optString("jjxcvideoToken"));
							ThreadPoolManager.getInstance().addTask(
									new uploadFileThread(0, url, null));
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

					@Override
					public void onLoading(int vurrent) {

					}

					@Override
					public void onFailure(String result) {
						Log.e(TAG, result);
					}
				});

	}

	/**
	 * 上传文件线程 type 0标识video 1 表示img
	 * 
	 */
	class uploadFileThread extends Thread {
		File uploadFile = null;
		String strToken;
		String fileUrl;
		int type;
		byte b[];

		public uploadFileThread(int type, String url, byte b[]) {
			this.strToken = getTokenType(type);
			this.fileUrl = url;
			this.b = b;
			this.type = type;
		}

		@Override
		public void run() {
			super.run();

			UploadOptions uploadOptions = new UploadOptions(null, null, true,
					new UpProgressHandler() {
						@Override
						public void progress(String key, double percent) {
							updateStatus(percent);
						}
					}, new UpCancellationSignal() {

						@Override
						public boolean isCancelled() {
							return cancelUpload;
						}
					});
			final String uploadFileKey = SDCardTools.getFileName(fileUrl);
			switch (type) {
			case 0:
				uploadManager.put(new File(fileUrl), uploadFileKey ,
						strToken, new UpCompletionHandler() {
							@Override
							public void complete(String k, ResponseInfo info,
									JSONObject res) {
								// res 包含hash、key等信息，具体字段取决于上传策略的设置。
								Log.i("qiniu", k + ",\r\n " + info + ",\r\n "
										+ res);
								// 判断视频是否上传成功
								if (info != null && info.isOK()) {
									ThreadPoolManager
											.getInstance()
											.addTask(
													new uploadFileThread(
															1,
															fileUrl,
															VideoTools
																	.Bitmap2Byte(VideoTools
																			.createVideoThumbnail(fileUrl))));
								}
							}

						}, new UploadOptions(null, null, true,
								new UpProgressHandler() {
									@Override
									public void progress(String key,
											double percent) {
										updateStatus(percent);
									}
								}, new UpCancellationSignal() {
									@Override
									public boolean isCancelled() {
										return cancelUpload;
									}
								}));
				break;
			case 1:
				uploadManager.put(b, uploadFileKey.replaceAll(".mp4", ".png"),
						strToken, new UpCompletionHandler() {
							@Override
							public void complete(String k, ResponseInfo info,
									JSONObject res) {
								// res 包含hash、key等信息，具体字段取决于上传策略的设置。
								Log.i("qiniu", k + ",\r\n " + info + ",\r\n "
										+ res);
								// 判断视频是否上传成功
								if (info != null && info.isOK()) {
									Log.i(TAG, "缩略图上传成功");
									addDiscover(uploadFileKey);
								}
							}
						}, uploadOptions);
				break;

			default:
				break;
			}

		}

	}

	/**
	 * 获取Token
	 * 
	 * @param type
	 *            0-video 1-img
	 * @return
	 */
	private String getTokenType(int type) {
		String token = "";
		switch (type) {
		case 0:
			token = SystemInfo.getTokenEntity().getJjxcvideoToken();
			break;
		case 1:
			token = SystemInfo.getTokenEntity().getJjxcimgToken();
			break;
		}
		return token;
	}

	/**
	 * 跟新上传状态
	 * 
	 * @param percentage
	 */
	private void updateStatus(final double percentage) {
		long now = System.currentTimeMillis();
		long deltaTime = now - uploadLastTimePoint;
		long currentOffset = (long) (percentage * uploadFileLength);
		long deltaSize = currentOffset - uploadLastOffset;
		if (deltaTime <= 100) {
			return;
		}

		final String speed = Tools.formatSpeed(deltaSize, deltaTime);
		// update
		uploadLastTimePoint = now;
		uploadLastOffset = currentOffset;

		AsyncRun.run(new Runnable() {
			@Override
			public void run() {
				int progress = (int) (percentage * 100);
				Log.i(TAG, progress + "%");
			}
		});
	}

	/**
	 * 上传成功后 提交到后台
	 * 
	 * @param uploadFileKey
	 * 
	 * @param key
	 *            文件名称
	 */
	private void addDiscover(String uploadFileKey) {
		String title = ((EditText) findViewById(R.id.video_title)).getText()
				.toString().trim();
		map = new HashMap<String, String>();
		map.put("userid", SystemInfo.getUserInfo().getUserid());
		map.put("access_token", SystemInfo.getTokenEntity().getToken()); // 验证码
		map.put("dis_type", "1");// 发现类型
		// 发现类型【1精彩2求助】（必）选1时，只需传dis_videourl（必）选2时，只需传dis_content（必）
		map.put("dis_title", title);// 发现标题
		map.put("dis_content", title);// 发现内容
		map.put("dis_imageurl", pathHead + pathName_img + App.DOMAINNAME_QINIU
				+ uploadFileKey.replaceAll(".mp4", ".png"));// 封面URL
		// http://img.irishud.com.cn/dist_20150917_004030.mp4_thumbail
		map.put("dis_videourl", pathHead + pathName_video
				+ App.DOMAINNAME_QINIU + uploadFileKey );// 视频url
		map.put("dis_lng", SharedPreTools.getString(this, Common.LNG, ""));// 当前经度
		map.put("dis_lat", SharedPreTools.getString(this, Common.LAT, ""));// 当前纬度
		map.put("dis_address", SharedPreTools.getString(this, Common.LOACTION, "未知"));// 定位地址
		map.put("address_flag", "0");// 定位是否打开
		HttpUtil.getInstance(this).Post(App.ZZD_REQUEST_ADDDISCOVER, map,
				new HttpResponseListener() {

					@Override
					public void onSuccess(RespEntity respEntity) {
						Log.i(TAG, "后台提交成功");
						dismissProgressDialog();
						showToast("视频上传成功");
						finish();
					}

					@Override
					public void onLoading(int vurrent) {

					}

					@Override
					public void onFailure(String result) {
						// TODO Auto-generated method stub

					}
				});
	}

}
